const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('-')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

/**
 * showLoading
 */
function showLoading() {
  //显示加载界面
  wx.showLoading({ // 显示加载中loading效果 
    title: "加载中",
    mask: true //开启蒙版遮罩
  });
}

/**
 * 关闭加载提示
 */
function closeLoading() {
  //隐藏加载界面
  wx.hideLoading();
}

/**
 * showToast
 * icon?: 'success' | 'error' | 'loading' | 'none'
 */
function showToast(msg, icon) {
  // 向带图标的toast只能容纳7个字的特性所做的妥协
  if (icon != undefined && icon != 'none' && msg != undefined && msg.length >= 7) {
    msg = msg.split(",")[0];
    msg = msg.split("，")[0];
  }
  wx.showToast({
    title: msg,
    icon: icon
  })
}

/**
 * 对字符串判空
 */
function isStrEmpty(string) {
  if (string == null || string == undefined || string == '' || string.replace(/\s+/g, '').length == 0) {
    return true;
  }
  return false;
}

/**
 * 将yyyy-MM-dd HH:mm:ss 切成 HH:mm
 */
function splitTimeStr1(str) {
  var time = str.split(' ');
  var result = time[1].split(':');
  var resultStr = result[0] + ':' + result[1];
  return resultStr;
}

/**
 * 处理时间格式
 */
function dealWithTime(timeStr) {
  var time = formatTime(new Date()).split(' ');
  var time1 = time[0].split('-');
  var time2 = time[1].split(':');
  // 开始格式化
  let a = timeStr.split(' ');
  let a1 = a[0].split("-");
  let a2 = a[1].split(":");
  //不是同一年
  if (a1[0] != time1[0]) {
    return a1[0] + "/" + a1[1];
  }
  //不是同一个月
  if (a1[1] != time1[1]) {
    return a1[1] + "/" + a1[2];
  }
  //昨天
  if (parseInt(time1[2]) - parseInt(a1[2]) == 1) {
    return "昨天 " + a2[0] + ':' + a2[1];
  }
  //同一天
  if (parseInt(time1[2]) - parseInt(a1[2]) == 0) {
    return a2[0] + ':' + a2[1];
  }
  return a1[1] + "/" + a1[2];
}

/**
 * 根据 1983-05-02 这个算年龄
 */
function getAgeByBirth(birthStr) {
  // 将日期字符串转换为 Date 对象
  var birthDate = new Date(birthStr);
  // 获取当前日期
  var currentDate = new Date();
  // 计算年龄
  var age = currentDate.getFullYear() - birthDate.getFullYear();
  // 如果当前月份小于出生月份，或者当前月份等于出生月份但是当前日期小于出生日期，则年龄减一
  if (currentDate.getMonth() < birthDate.getMonth() ||
    (currentDate.getMonth() === birthDate.getMonth() && currentDate.getDate() < birthDate.getDate())) {
    age--;
  }
  return age;
}

module.exports = {
  formatTime,
  showLoading,
  closeLoading,
  showToast,
  isStrEmpty,
  splitTimeStr1,
  dealWithTime,
  getAgeByBirth
}